package com.xvyy.tingshu.dispatch.handler;

import com.xvyy.tingshu.user.client.UserInfoFeignClient;

import com.xvyy.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.xvyy.tingshu.model.dispatch.XxlJobLog;
import com.xvyy.tingshu.search.client.SearchFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ClassName: DispatchHandler
 * Package: com.xvyy.tingshu.dispatch.handler
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/2/15 - 11:44
 * @Version: v1.0
 */
@Component
public class DispatchHandler {

    @Autowired
    private SearchFeignClient searchFeignClient;
    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    /**
     * @Description: 定时任务：更新预热的排行榜
     */
    @XxlJob("updatePreHitRank")
    public void updatePreHitRank() {
        Long startTime = 0L;
        // 1. 记录任务信息
        XxlJobLog xxlJobLog = new XxlJobLog();
        long jobId = XxlJobHelper.getJobId();
        xxlJobLog.setJobId(jobId);
        // 2. 调用远程服务，将数据同步到ES
        try {
            startTime = System.currentTimeMillis();
            searchFeignClient.preHitRank();
            xxlJobLog.setStatus(1);
            xxlJobLogMapper.insert(xxlJobLog);
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            Long endTime = 0L;
            Integer wasteTime = (int) (endTime - startTime);
            xxlJobLog.setTimes(wasteTime);
        }
    }

    /**
     * @Description: 定时任务：判断用户vip时间是否到期
     */
    @XxlJob("updateVipExpireStatus")
    public void updateVipExpireStatus() {
            Long startTime = 0L;
            // 1. 记录任务信息
            XxlJobLog xxlJobLog = new XxlJobLog();
            long jobId = XxlJobHelper.getJobId();
            xxlJobLog.setJobId(jobId);
            // 2. 调用远程服务，将数据同步到ES
            try {
                startTime = System.currentTimeMillis();
                userInfoFeignClient.updateVipExpireStatus();
                xxlJobLog.setStatus(1);
                xxlJobLogMapper.insert(xxlJobLog);
            } catch (Exception e) {
                xxlJobLog.setStatus(0);
                xxlJobLog.setError(e.getMessage());
                throw new RuntimeException(e);
            } finally {
                Long endTime = 0L;
                Integer wasteTime = (int) (endTime - startTime);
                xxlJobLog.setTimes(wasteTime);
            }
    }

}
